package com.wondedDream.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtils.class);

    private static final String SECRET_KEY = "your_secret_key";
    private static final long JWT_TOKEN_VALIDITY = 24 * 60 * 60 * 1000; // 一天的毫秒数

    public String generateToken(String subject) {
        return Jwts.builder()
             .setSubject(subject)
             .setIssuedAt(new Date(System.currentTimeMillis()))
             .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
             .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
             .compact();
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public String getSubject(String token) {
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    // 解析JWT
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    // 验证JWT
    public static boolean validateToken(String token, String username) {
        final String extractedUsername = parseToken(token).getSubject();
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }

    private static boolean isTokenExpired(String token) {
        return parseToken(token).getExpiration().before(new Date());
    }

    /**
     * 通过Token获取token中的用户名
     *
     * @param token 令牌
     * @param secret 秘钥
     * @return String
     */
    public static String getUsernameFromToken(String token, String secret) {
        String username = null;
        try {
            final Claims claims = getClaimsFromToken(token, secret);
            if (claims != null) {
                username = claims.getSubject();
            }
        } catch (Exception e) {
            LOGGER.error("Error getUsernameFromToken: ", e);
        }
        return username;
    }


    /**
     * 从token中读取Claims对象
     *
     * @param token 令牌
     * @param secret 加密秘钥
     * @return 对象
     */
    public static Claims getClaimsFromToken(String token, String secret) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            LOGGER.error("secret:{}, token:{}", secret, token);
            LOGGER.error("Error getClaimsFromToken: ", e);
        }
        return claims;
    }
}